package cn.itcast.goods.user.service;

import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.user.dao.UserDao;
import cn.itcast.goods.user.domain.User;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
import javax.mail.MessagingException;
import javax.mail.Session;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
public class UserService {
    UserDao dao=new UserDao();
    public  boolean AJAXcheckUserName(String name)
    {
        boolean boo=dao.AJAXcheckUserName(name);
        return boo;
    }
    public  boolean AJAXcheckEmail(String email)
    {
        boolean boo=dao.AJAXcheckEmail(email);
        return boo;
    }
    public  void add(User user)
    {
        //补齐信息
        user.setUid(CommonUtils.uuid());
        user.setActivationCode(CommonUtils.uuid()+CommonUtils.uuid());
        user.setStatus(false);
        //向数据库添加数据
        dao.addUser(user);
        //发送邮件，得到激活码
        //加载配置文件内容
        Properties properties=new Properties();
        try {
            properties.load(this.getClass().getResourceAsStream("email_template.properties"));
        }
        catch (IOException e)
        {
            throw  new RuntimeException(e);
        }
        //登录邮件服务器主机，得到session
        String host=properties.getProperty("host");//服务器主机名
        String name=properties.getProperty("username");//登录名
        String pass=properties.getProperty("password");//密码
        Session session=MailUtils.createSession(host,name,pass);
        //创建Mail对象
        String from=properties.getProperty("from");
        String to=user.getEmail();
        String subject=properties.getProperty("subject");
        //MessageFormat.format会把第一个（0），用第二个参数来替代
        //例如：MessageFormat.format（"{0},{1}","你"，"好"）;返回:你好
        String content= MessageFormat.format(properties.getProperty("content"),user.getActivationCode());
        Mail mail=new Mail(from,to,subject,content);
        //发送邮件
        try {
            MailUtils.send(session, mail);
        }
        catch (MessagingException e)
        {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
